package com.dynabook.ems.disruptor.Excel;

import com.dynabook.ems.model.dto.EmsDataDTO;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class EmsDisruptorProducer {

    @Resource
    private Disruptor<EmsDataEvent> emsDisruptor;

    public void pushData(List<EmsDataDTO> params) {
        RingBuffer<EmsDataEvent> ringBuffer = emsDisruptor.getRingBuffer();
        long next = ringBuffer.next();
        try {
            EmsDataEvent event = ringBuffer.get(next);
            // 创建新副本，避免引用外部列表导致数据被修改
            List<EmsDataDTO> copy = new ArrayList<>(params);
            event.setParams(copy); // 确保每次都是新数据
            log.info("pushData:{}", copy);
        } finally {
            ringBuffer.publish(next);
        }
    }


    /**
     * 优雅停机
     */
    @PreDestroy
    public void shutdown() {
        emsDisruptor.shutdown();
    }
}
